package com.example.tb_base.base_viewmodel_activity_fragment

import android.os.Bundle
import android.widget.Toast
import androidx.viewbinding.ViewBinding
import com.example.tb_base.BaseRepository
import com.example.tb_base.DataState
import com.example.tb_base.BaseViewModel
import com.example.tb_base.LoadingState
import com.example.tb_base.base_viewbinding_activity_fragment.BaseViewBindingActivity

/**
 * 基于ViewBinding和ViewModel的Activity基类，统一处理布局加载、WindowInsets适配等通用逻辑。
 * 子类只需实现抽象方法即可快速搭建自己的Activity。
 */
abstract class BaseViewModelActivity<V : ViewBinding, VM : BaseViewModel<BaseRepository>> :
    BaseViewBindingActivity<V>() {

    protected val viewModel: VM by lazy {
        createViewModel()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initObservers()
    }

    protected abstract fun createViewModel(): VM
    protected open fun initObservers() {
        viewModel.loadingDataState.observe(this) {
            when (it.state) {
                DataState.STATE_LOADING ->
                    showLoading()

                else ->
                    dismissLoading(it)
            }
        }
    }

    open fun showLoading(msg: String? = "请求中") {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }

    open fun dismissLoading(loadingState: LoadingState) {
        Toast.makeText(this, "${loadingState.state.name} ", Toast.LENGTH_SHORT).show()
    }
}